<template>
	<div class="tabelContainer">
		<basic-container>
			<avue-crud :option="option" :table-loading="loading" :data.sync="data" :page.sync="page" :permission="permissionList" :before-open="beforeOpen" v-model="form" ref="crud" @row-update="rowUpdate" @row-save="rowSave" @row-del="rowDel" @search-change="searchChange" @search-reset="searchReset" @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoad">
				<template slot="menuLeft">
					<el-button type="danger" size="small" icon="el-icon-delete" plain v-if="this.permission.trainplan_delete" @click="handleDelete">删 除
					</el-button>
					<el-button type="warning" size="small" plain v-if="this.permission.trainplan_export" icon="el-icon-download" @click="handleExport">导出
					</el-button>
				</template>
				<template slot="startTimeSearch" slot-scope="{disabled,size}">
					<div class="search-date">
						<el-date-picker v-model="dateFrom" type="date" size="small" placeholder="请选择开始日期" value-format="yyyy-MM-dd" :picker-options="pickerOption"></el-date-picker>
					</div>
				</template>
				<!-- 自定义培训人列 -->
				<template slot-scope="{row}" slot="staffName">
					<el-popover placement="right" title="培训人:" width="200" trigger="click" :content="row.staffName">
						<el-button type="text" slot="reference">详情</el-button>
					</el-popover>
				</template>

				<!-- 自定义培训人信息表 -->
				<template slot="infoForm" slot-scope="scope">
					<avue-crud :option="infoOption" :data="infoData" :table-loading="infoLoading" :page.sync="infoPage" :search.sync="infosearch" ref='crud' @search-change="infosearchChange" @search-reset="infoSearchReset" @selection-change="selectionInfoChange" @current-change="currentChange" @size-change="sizeChange" @refresh-change="refreshChange" @on-load="onLoadinfo">
						<!--      自定义子表中性别列 -->
						<template slot="sex" slot-scope="scope">
							<div v-if="scope.row.sex === '1'">男</div>
							<div v-else-if="scope.row.sex === '2'">女</div>
							<div v-else>-</div>
						</template>
						<template slot="menuLeft">
							<el-button type="primary" size="small" @click="addInfo">添加培训人</el-button>
						</template>
					</avue-crud>
				</template>

				<!-- 自定义已添加培训人列表 -->
				<template slot="addInfoForm" slot-scope="scope">
					<avue-crud :option="addInfoOption" :data.sync="addData" @selection-change="addInfoChange" ref='crud'>
						<template slot="menuLeft">
							<el-tag type="info">已添加培训人列表</el-tag>
							<el-button type="primary" size="small" @click="delInfo">删除培训人</el-button>
						</template>
					</avue-crud>
				</template>

				<!-- 自定义编辑培训人列表 -->
				<template slot="editInfoForm" slot-scope="scope">
					<avue-crud :option="selectedInfoOption" :data.sync="editData" @selection-change="selectedInfoChange" ref='crud'>

						<template slot="menuLeft">
							<el-tag type="info">编辑培训人列表</el-tag>
							<el-button type="primary" size="small" @click="delEdit">删除培训人</el-button>
						</template>
					</avue-crud>
				</template>

			</avue-crud>
		</basic-container>
	</div>
</template>

<script>
	import { getList, getDetail, getStaffListPage, getStaffList, add, update, remove, editRemove } from "@/api/dust/trainplan";
	import { mapGetters } from "vuex";
	import { dateFormat } from "@/util/date";
	import website from '@/config/website';
	import { getToken } from '@/util/auth';

	export default {
		data() {
			return {
				dateFrom: '',
				search: {},
				infosearch: {},
				form: {},
				staffForm: {},
				query: {},
				infoQuery: {},
				staffQuery: {},
				//子表格配置
				infoOption: {
					searchMenuSpan: 12,
					selection: true,
					tip: false,
					menu: false,
					addBtn: false,
					column: [{
							label: '岗位名称',
							prop: 'post',
							hide: true,
							search: true,
							searchSpan: 6,
							searchPlaceholder: '请选择',
							type: 'select',
							dicUrl: '/api/squirrel-ficm/staffinfo/getPostList',
							props: {
								label: "postName",
								value: "id"
							},
						},
						{
							label: '姓名',
							prop: 'name',
							search: true,
							searchPlaceholder: '请输入姓名',
						},
						{
							label: '性别',
							prop: 'sex',
							slot: true,
						},
						{
							label: '工号',
							prop: 'workNum',
						},
					]
				},
				//新增表格配置
				addInfoOption: {
					selection: true,
					// searchMenuSpan:12,
					refreshBtn: false,
					columnBtn: false,
					tip: false,
					menu: false,
					addBtn: false,
					column: [{
							label: 'id',
							prop: 'id',
							showColumn: false,
						},
						{
							label: '岗位名称',
							prop: 'postName',
						},
						{
							label: '姓名',
							prop: 'name',
						}
					]
				},
				//编辑表格配置
				selectedInfoOption: {
					selection: true,
					// searchMenuSpan:12,
					refreshBtn: false,
					columnBtn: false,
					tip: false,
					menu: false,
					addBtn: false,
					column: [{
							label: 'id',
							prop: 'id',
							showColumn: false,
						},
						{
							label: '岗位名称',
							prop: 'postName',
						},
						{
							label: '姓名',
							prop: 'staffName',
						}
					]
				},

				//表格加载
				loading: true,
				infoLoading: true,
				staffLoading: true,

				//表格页面配置
				page: {
					pageSize: this.$pageSize,
					currentPage: 1,
					total: 0
				},
				infoPage: {
					pageSize: this.$pageSize,
					currentPage: 1,
					total: 0
				},
				staffPage: {
					pageSize: this.$pageSize,
					currentPage: 1,
					total: 0
				},

				selectionList: [], //父表所选列的列表
				selectionInfoList: [], //子表所选列的列表
				addInfoList: [], //增加表所选的列表
				selectedInfoList: [], //编辑表所选的列表

				//主表单配置
				option: {

					calcHeight: 30,
					tip: false,
					menuWidth: 200,
					searchShow: true,
					searchMenuSpan: 6,
					border: true,
					index: true,
					viewBtn: true,
					selection: true,
					dialogClickModal: false,
					menuAlign: 'center',

					column: [{
							label: "所属项目",
							width: "100%",
							labelWidth: 110,
							search: true,
							searchSpan: 5,
							searchPlaceholder: '请选择',
							type: 'select',
							prop: "deptInfoId",
							dicUrl: '/api/squirrel-ficm/deptinfo/getProjectList',
							props: {
								label: "deptName",
								value: "id"
							},
							rules: [{
								required: true,
								message: "请输入所属项目",
								trigger: "blur"
							}]
						},
						{
							label: "培训计划名称",
							width: "100%",
							searchLabelWidth: 100,
							labelWidth: 110,
							search: true,
							searchSpan: 5,
							searchPlaceholder: '请输入',
							prop: "name",
							rules: [{
								required: true,
								message: "请输入培训计划名称",
								trigger: "blur"
							}]
						},
						{
							label: "培训地点",
							labelWidth: 110,
							prop: "courseLocation",
							rules: [{
								required: true,
								message: "请输入培训地点",
								trigger: "blur"
							}]
						},
						{
							label: "培训方式",
							labelWidth: 110,
							prop: "trainMethods",
							rules: [{
								required: true,
								message: "请输入培训方式",
								trigger: "blur"
							}]
						},
						{
							label: "培训课程",
							labelWidth: 110,
							prop: "trainCourse",
							rules: [{
								required: true,
								message: "请输入培训课程",
								trigger: "blur"
							}]
						},
						{
							label: "培训人",
							labelWidth: 110,
							addDisplay: false,
							//addDisabled:true,

							editDisplay: false,
							//editDisabled:true,
							placeholder: "请添加培训人 ",
							prop: "staffName",
							slot: true,
							rules: [{
								required: false,
								message: "请添加培训人",
								trigger: "blur"
							}]
						},
						{
							label: "培训人ids",
							labelWidth: 110,
							showColumn: false,
							prop: "ids",
							addDisplay: false,
							addDetail: true,
							addDisabled: true,

							editDisplay: false,
							editDetail: true,
							editDisabled: true,
							viewDisplay: false,
						},
						{
							label: "讲师",
							labelWidth: 110,
							prop: "lecturer",
							rules: [{
								required: true,
								message: "请输入讲师",
								trigger: "blur"
							}]
						},
						{
							label: "编制人",
							labelWidth: 110,
							prop: "preparer",
							rules: [{
								required: true,
								message: "请输入编制人",
								trigger: "blur"
							}]
						},
						{
							label: "培训开始时间",
							labelWidth: 110,
							prop: "startTime",
							type: "datetime",
							width: "140%",
							search: true,
							searchslot: true,
							searchRange: true,
							searchSpan: 6,
							searchLabelWidth: 100,
							format: "yyyy-MM-dd HH:mm:ss",
							valueFormat: "yyyy-MM-dd HH:mm:ss",
							placeholder: "请选择培训开始时间",
							rules: [{
								required: true,
								message: "请选择培训开始时间",
								trigger: "blur"
							}]
						},
						{
							label: "培训结束时间",
							labelWidth: 110,
							prop: "endTime",
							type: "datetime",
							width: "140%",
							format: "yyyy-MM-dd HH:mm:ss",
							valueFormat: "yyyy-MM-dd HH:mm:ss",
							placeholder: "请选择培训结束时间",
							rules: [{
								required: true,
								message: "请选择培训结束时间",
								trigger: "blur"
							}]
						},
						{
							labelWidth: 0,
							label: '',
							prop: 'info',
							span: 24,
							viewDisplay: false,
							//editDisplay:false,
							hide: true,
							formslot: true,
						},
						{
							labelWidth: 0,
							//label: '新增培训人',
							prop: 'addInfo',
							span: 24,
							//addDisplay:false,
							viewDisplay: false,
							editDisplay: false,
							hide: true,
							formslot: true,
						},
						{
							labelWidth: 0,
							//label: '编辑培训人',
							prop: 'editInfo',
							span: 24,
							addDisplay: false,
							viewDisplay: false,
							//editDisplay:false,
							hide: true,
							formslot: true,
						},
					],
				},
				data: [], //父表数据
				infoData: [], //子表数据
				addData: [], //添加数据
				editData: [],
				selectedInfoData: [], //编辑数据
				// editIds:[]
			};
		},
		mounted: function() {
			window.vue = this;
		},
		watch: {
			//监听表单的所属项目，加载对应的员工
			'form.deptInfoId' () {
				if(this.form.deptInfoId !== '') {
					this.infoQuery.deptInfoId = this.form.deptInfoId;
          this.infoPage.currentPage = 1;
					this.onLoadinfo(this.infoPage, this.infoQuery);
				}
			},
		},
		computed: {
			...mapGetters(["permission"]),
			permissionList() {
				return {
					//操作栏按钮选项
					addBtn: this.vaildData(this.permission.trainplan_add, false),
					viewBtn: this.vaildData(this.permission.trainplan_view, false),
					delBtn: this.vaildData(this.permission.trainplan_delete, false),
					editBtn: this.vaildData(this.permission.trainplan_edit, false),
					exportBtn: this.vaildData(this.permission.trainplan_export, false)
				};
			},
			deptInfoId() {
				let deptInfoId = this.infoQuery.deptInfoId;
				return deptInfoId;
			},
			//主表所选列的主键ids，用,隔开
			ids() {
				let ids = [];
				this.selectionList.forEach(ele => {
					ids.push(ele.id);
				});
				return ids.join(",");
			},
			//增加表所选列的主键staffIds,用,隔开
			staffIds() {
				let staffIds = [];
				this.addData.forEach(ele => {
					staffIds.push(ele.id);
				});
				return staffIds.join(",");
			},
			editIds() {
				let editIds = [];
				this.editData.forEach(ele => {
					editIds.push(ele.staffId);
				});
				return editIds.join(",");
			},
		},
		methods: {
			handleExport() {
				this.$confirm("是否导出培训计划数据?", "提示", {
					confirmButtonText: "确定",
					cancelButtonText: "取消",
					type: "warning"
				}).then(() => {
					const searchForm = this.$refs.crud.searchForm;
					window.open(`/api/squirrel-train/trainplan/export?${this.website.tokenHeader}=${getToken()}&deptInfoId=${searchForm.deptInfoId}&name=${searchForm.name}&time=${searchForm.startTime}`);
				});
			},
			rowSave(row, done, loading) {
				if(this.addData.length == 0) {
					this.$message({
						type: "warning",
						message: "未添加培训人!"
					});
				} else {
					add(row).then(res => {
						this.onLoad(this.page);
						this.$message({
							type: "success",
							message: "保存成功!"
						});
						done();
					}, error => {
						loading();
						window.console.log(error);
					});
				}
			},
			//行内编辑--修改
			rowUpdate(row, index, done, loading) {
				console.log(this.editIds)
				row.ids = this.editIds;
				update(row).then(() => {
					this.onLoad(this.page);
					this.$message({
						type: "success",
						message: "操作成功!"
					});
					done();
				}, error => {
					loading();
					console.log(error);
				});
			},
			//行内删除
			rowDel(row) {
				this.$confirm("确定将选择数据删除?", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning"
					})
					.then(() => {
						return remove(row.id);
					})
					.then(() => {
						this.onLoad(this.page);
						this.$message({
							type: "success",
							message: "操作成功!"
						});
					});
			},
			handleDelete() {
				if(this.selectionList.length === 0) {
					this.$message.warning("请选择至少一条数据");
					return;
				}
				this.$confirm("确定将选择数据删除?", {
						confirmButtonText: "确定",
						cancelButtonText: "取消",
						type: "warning"
					})
					.then(() => {
						return remove(this.ids);
					})
					.then(() => {
						this.onLoad(this.page);
						this.$message({
							type: "success",
							message: "操作成功!"
						});
						this.$refs.crud.toggleSelection();
					});
			},

			//父表打开前的处理
			beforeOpen(done, type) {
				if(["add"].includes(type)) {
					//新增按钮触发后，将新增数据表置空
					this.addData = [];
				} else if(["view"].includes(type)) {
					getDetail(this.form.id).then(res => {
						this.form = res.data.data;
					});
				} else if(["edit"].includes(type)) {
					getDetail(this.form.id).then(res => {
						this.form = res.data.data;
					});
					//根据trainPlanId查询该行对应的人员表，加载已编辑列表
					this.staffQuery.trainPlanId = this.form.id;
					getStaffList(this.staffPage.currentPage, this.staffPage.pageSize, this.staffQuery).then(res => {
						const data = res.data.data;
						this.editData = data.records;
					});
				};
				done();
			},
			addInfo() {
				//增加子表数据加载
				//合并且去重函数
				function MergeArray(arr1, arr2) {
					var _arr = new Array();
					for(var i = 0; i < arr1.length; i++) {
						_arr.push(arr1[i]);
					}
					for(var i = 0; i < arr2.length; i++) {
						var flag = true;
						for(var j = 0; j < arr1.length; j++) {
							if(arr2[i] == arr1[j]) {
								flag = false;
								break;
							}
						}
						if(flag) {
							_arr.push(arr2[i]);
						}
					}
					return _arr;
				}

				this.addData = MergeArray(this.addData, this.selectionInfoList);
				//给表单的员工ids赋值
				this.form.ids = this.staffIds;

				if(this.editData.length != 0) {
					this.editData = this.editData.map(o => {
						return {
							postName: o.postName,
							staffId: o.staffId,
							staffName: o.staffName,
						}
					})
					this.selectionInfoList = this.selectionInfoList.map(o => {
						return {
							// deptInfoId:'',deptName:'',id:'',isSignIn:'',planName:'',post:'',
							// postName:o.postName,
							// staffId:o.id,
							// staffName:o.name,
							// trainCourse:'',trainPlanId:'',workNum:'',
							postName: o.postName,
							staffId: o.id,
							staffName: o.name,
						}
					})
					let json = this.editData.concat(this.selectionInfoList);
					let newJson = [];
					for(let item1 of json) { //循环json数组对象的内容
						let flag = true; //建立标记，判断数据是否重复，true为不重复
						for(let item2 of newJson) { //循环新数组的内容
							if(item1.staffId == item2.staffId) { //让json数组对象的内容与新数组的内容作比较，相同的话，改变标记为false
								flag = false;
							}
						}
						if(flag) { //判断是否重复
							newJson.push(item1); //不重复的放入新数组。  新数组的内容会继续进行上边的循环。
						}
					}
					this.editData = newJson;
					// this.editData = MergeArray(this.editData,this.selectionInfoList);
					this.form.ids = this.editIds;
				};

				this.selectionInfoList = [];
			},

			//新增事件的删除
			delInfo() {
				//两个列表去重，完成删除操作
				let delList = this.addData.filter(items => {
					if(!this.addInfoList.includes(items)) return items;
				})
				this.addData = delList;
				//给表单的员工ids赋值
				this.form.ids = this.staffIds;
			},

			//编辑事件的删除
			delEdit() {
				let delEditList = this.editData.filter(items => {
					if(!this.selectedInfoList.includes(items)) return items;
				})
				this.editData = delEditList;
				this.form.ids = this.editIds;
			},

			searchReset() {
				this.query = {};
				// 自定义时间查询，手动清空输入框
				this.dateFrom = '';
				this.onLoad(this.page);
			},
			//子表搜索栏清空
			infoSearchReset() {
				this.infoQuery = {};
				//表单所选所属项目也为空
				this.form.deptInfoId = '';
				this.onLoadinfo(this.infoPage);
			},

			searchChange(params, done) {
				this.query = params;
				// 自定义查询，手动添加键值对  'start'对应 dateFrom
				this.query['time'] = this.dateFrom;
				this.page.currentPage = 1;
				this.onLoad(this.page, params);
				done();
			},
			//员工查询
			infosearchChange(params, done) {
				this.infoQuery = params;
				//保留所属项目搜索
				this.infoQuery.deptInfoId = this.form.deptInfoId;
				this.infoPage.currentPage = 1;
				this.onLoadinfo(this.infoPage, params);
				done();
			},

			//主表选择列改变
			selectionChange(list) {
				this.selectionList = list;
			},
			//员工信息表选择列改变
			selectionInfoChange(list) {
				this.selectionInfoList = list;
			},
			//添加信息列选择列改变
			addInfoChange(list) {
				this.addInfoList = list;
			},
			//编辑信息列选择列改变
			selectedInfoChange(list) {
				this.selectedInfoList = list;
			},

			//选择列清空
			selectionClear() {
				this.selectionList = [];
				//this.$refs.crud.toggleSelection();
			},
			selectionInfoClear() {
				this.selectionInfoList = [];
				//this.$refs.crud.toggleSelection();
			},
			selectedInfoClear() {
				this.selectedInfoList = [];
				//this.$refs.crud.toggleSelection();
			},

			//当前页改变
			currentChange(currentPage) {
				this.page.currentPage = currentPage;
				this.infoPage.currentPage = currentPage;
			},

			//页面大小改变
			sizeChange(pageSize) {
				this.page.pageSize = pageSize;
				this.infoPage.pageSize = pageSize;
			},

			//列表刷新
			refreshChange() {
				this.onLoad(this.page, this.query);
				this.onLoadinfo(this.infoPage, this.infoQuery);
			},

			//主表格数据加载
			onLoad(page, params = {}) {
				this.loading = true;
				getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
					const data = res.data.data;
					this.page.total = data.total;
					this.data = data.records;
					this.loading = false;
					this.selectionClear();
				});
			},
			//子表格数据加载
			onLoadinfo(infoPage, params = {}) {
				this.infoLoading = true;
				getStaffListPage(infoPage.currentPage, infoPage.pageSize, Object.assign(params, this.infoQuery)).then(res => {
					const data = res.data.data;
					this.infoPage.total = data.total;
					this.infoData = data.records;
					this.infoLoading = false;
					this.selectionInfoClear();
				});
			},
			//编辑子表格数据加载
			onLoadstaffList(staffPage, params = {}) {
				this.staffLoading = true;
				getStaffList(staffPage.currentPage, staffPage.pageSize, Object.assign(params, this.staffQuery)).then(res => {
					const data = res.data.data;
					this.staffPage.total = data.total;
					this.selectedInfoData = data.records;
					this.staffLoading = false;
					this.selectedInfoClear();
				});
			},
		}
	};
</script>

<style scoped>
	.search-date {
		display: flex;
		height: 33px;
		line-height: 33px;
	}
</style>
